import { t } from 'i18next'
import createVanilla from 'zustand/vanilla'
import create from 'zustand'
import { fetchCreateSaveVideo, fetchGetAllServers, fetchGetAllVideo, fetchStartVideo } from '@/api/manager/mccMtVideo'
import { useMccStore } from '../../store'
import Alert from '@/components/Alert'
import {
	VideoMtProps,
	FetchGetAllVideoReturnProps,
	FetchStartVideoParamsProps,
	MtVideosProps,
	FetchGetAllServersReturnProps,
} from '@/api/manager/mccMtVideo/interface'
import { store as paramsStore } from '@/pages/manager/blocks/main/store'
import { buildNameTime, replaceSpaceBk } from '@/utils/format'

/** 编辑按钮进来、创建录像按钮进来、详情按钮进来、开始录像按钮进来、终端录像按钮进来的*/
export type VideoModalType = 'update' | 'create' | 'detail' | 'start' | 'terminalRecording'
export interface VrsModalProps {
	/**是否展示录播弹窗 */
	isShow: boolean
	/**弹窗的类型：编辑按钮进来、创建录像按钮进来、详情按钮进来、开始录像按钮进来*/
	type: VideoModalType
	/**弹窗的底部按钮 */
	modalBack: VrsModalBackProps
	videos: MtVideosProps[]
}

export interface VrsModalBackProps {
	/**录播服务器唯一标识*/
	vrs_id?: string
	/**录播服务器名*/
	vrs_name?: string
	/**录像文件名*/
	rec_file?: string
	/**发布模式不发布*/
	publish_mode?: number
}

type MccMtVideoStore = StateType & {
	reset: () => void
	/**开始录像按钮 */
	startMtsVideo: (data: VideoMtProps[], type: VideoModalType) => void
	/**创建录像按钮 */
	createMtsVideo: (data: VideoMtProps[], type: VideoModalType) => void
	commonMtsVideo: (data: VideoMtProps[], type: VideoModalType) => void
	getVrsServerList: () => Promise<FetchGetAllServersReturnProps[]>
	cancelParamsStoreCheck: () => void
	setModalInfo: (info: Partial<VrsModalProps>) => void
	/**请求 发送开始录像数据 */
	sendStartParam: (vrs: VrsModalBackProps, videos: MtVideosProps[]) => void
	/**请求 发送创建录像数据 */
	sendCreateParam: (vrs: VrsModalBackProps, videos: MtVideosProps[]) => void
	commonSendVrsParam: (vrs: VrsModalBackProps, videos: MtVideosProps[], type: 'start' | 'create') => void
	/**在cometd中调用的 来更改某条录像数据 */
	cometdRerenderVideo: (videoVo: FetchGetAllVideoReturnProps) => void
	/**接口获取所有录播数据 */
	getAllVideo: () => Promise<FetchGetAllVideoReturnProps[]>
	reload: () => void
	setSelectedRows: (rows: FetchGetAllVideoReturnProps[]) => void
	setSelectedRowIds: (ids: string[]) => void
	justIsHadInVrsList: (result: VideoMtProps[]) => Promise<VideoMtProps[] | false>
	rec: (result: VideoMtProps[], type: VideoModalType) => void
	/** 存储终端录像数据 */
	storeRecord: (d: FetchGetAllVideoReturnProps) => void
}
type StateType = {
	/**录播服务器列表 */
	vrsServerList?: FetchGetAllServersReturnProps[]
	/**所有录播列表 */
	allVideo?: FetchGetAllVideoReturnProps[]
	modalInfo: VrsModalProps
	selectedRows: FetchGetAllVideoReturnProps[]
	selectedRowIds: string[]
	recordRecIng: FetchGetAllVideoReturnProps[]
}
const defaultModalInfo: VrsModalProps = {
	isShow: false,
	type: 'update',
	modalBack: {
		vrs_id: '',
		vrs_name: '',
		rec_file: '',
		publish_mode: 1,
	},
	videos: [],
}
const initialState: StateType = {
	vrsServerList: undefined,
	allVideo: undefined,
	modalInfo: defaultModalInfo,
	selectedRows: [],
	selectedRowIds: [],
	recordRecIng: [],
}
export const store = createVanilla<MccMtVideoStore>((set, get) => ({
	...initialState,
	reset: () => set(initialState),
	setSelectedRows: (rows) => {
		set({ selectedRows: rows })
	},
	setSelectedRowIds: (ids) => {
		set({ selectedRowIds: ids })
	},
	setModalInfo: (info) => {
		let modalInfo = get().modalInfo
		set({
			modalInfo: {
				...modalInfo,
				...info,
			},
		})
	},
	/**接口获取所有录播数据 */
	getAllVideo: () => {
		return new Promise((resolve, reject) => {
			const meetingMoid: string = useMccStore.getState().mccInfo.meetingMoid
			fetchGetAllVideo({ meeting_id: meetingMoid })
				.then((data) => {
					//不渲染已停止的录像
					let newData = data.filter((item) => {
						return item.state !== 0
					})
					set({ allVideo: newData })
					resolve(newData)
				})
				.catch(() => {
					reject([])
				})
		})
	},
	getVrsServerList: () => {
		return new Promise((resolve, reject) => {
			const meetingMoid: string = useMccStore.getState().mccInfo.meetingMoid
			fetchGetAllServers({ meeting_id: meetingMoid })
				.then((data) => {
					set({ vrsServerList: data })
					if (!data.length) {
						Alert(t('当前环境缺少录播服务器'))
					}
					resolve(data)
				})
				.catch(() => {
					reject([])
				})
		})
	},
	reload: () => {
		set({ selectedRows: [] })
		set({ selectedRowIds: [] })
		get().getAllVideo()
	},
	/**在cometd中调用的 来更改某条录像数据 */
	/**TODO scy 没有测试videoVo给到的是什么 */
	cometdRerenderVideo: (videoVo) => {
		// console.log(videoVo, 'videoVo===============')
		let allVideo = get().allVideo
		let newData: FetchGetAllVideoReturnProps[] = []
		let findItem = allVideo?.find((item) => item.id === videoVo.id)
		if (findItem) {
			//修改某一条数据
			newData = allVideo!.map((item) => {
				return item.id === videoVo.id ? { ...item, ...videoVo } : item
			})
		} else {
			//属于直接开始录像
			if (allVideo) {
				newData = [...allVideo, { ...videoVo }]
			} else {
				newData = [{ ...videoVo }]
			}
		}
		set({
			allVideo: newData.filter((item) => item.state !== 0), //不渲染已停止的录像
		})
		
		let modalInfo = get().modalInfo
		if (modalInfo.isShow && modalInfo.type === 'detail' && modalInfo.videos[0].id === videoVo.id) {
			//详情展示，动态变动时间
			let x = modalInfo.videos[0]
			x.duration = videoVo.duration
			get().setModalInfo({
				videos: [{ ...x }],
			})
		}
	},
	/** checkbox取消选择*/
	cancelParamsStoreCheck: () => {
		if (useMccStore.getState().curPage === 'mt_record') {
			paramsStore.setState({
				actionButtonList: ['startMtVmp', 'createMtVmp', 'checkAll'],
			})
		}
	},
	commonMtsVideo: async (result, type) => {
		let videos = await get().justIsHadInVrsList(result)
		if (!videos) {
			return
		}
		await get().getVrsServerList()
		let modalInfo = get().modalInfo
		let vrsList = get().vrsServerList
		if (vrsList && vrsList.length) {
			if (vrsList.length > 1) {
				// 在弹窗中操作
				const videoName = result[0] ? replaceSpaceBk(result[0].mt?.name || '') + buildNameTime() : ''
				get().setModalInfo({
					isShow: true,
					type: type,
					videos: videos,
					modalBack: {
						...modalInfo.modalBack,
						vrs_id: '',
						publish_mode: 1,
						rec_file: type === 'terminalRecording' ? videoName : modalInfo.modalBack.vrs_name || '',
					},
				})
			} else if (vrsList.length === 1) {
				let vrs = {
					vrs_id: vrsList[0].vrs_id,
					vrs_name: vrsList[0].server_name,
					rec_file: '',
					publish_mode: 1,
				}
				if (type === 'start') {
					//开始录像
					get().sendStartParam(vrs, videos)
				} else {
					//创建录像
					get().sendCreateParam(vrs, videos)
				}
			}
		} else {
			Alert(t('无录播服务器'))
			return false
		}
	},
	justIsHadInVrsList: async (result) => {
		await get().getAllVideo()
		let videoList = get().allVideo || []
		let filterList: VideoMtProps[] = [] //不存在列表中的
		let flag = false
		let nameArr: string[] = []
		
		result.forEach((item) => {
			if (videoList.findIndex((j) => j.mt && item.mt?.mt_key === j.mt.mt_key && j.state !== 0) !== -1) {
				flag = true
				item.mt?.name && nameArr.push(item.mt.name)
			} else {
				filterList.push(item)
			}
		})

		if (flag) {
			Alert(t('{{name}}已存在于终端录像列表中', { name: nameArr.join(',') }))
		}
		if (filterList.length === 0) {
			get().cancelParamsStoreCheck()
			return false
		}
		return filterList
	},
	/**开始录像按钮 */
	startMtsVideo: (result, type) => {
		get().commonMtsVideo(result, type)
	},
	/**请求 发送开始录像数据 */
	sendStartParam: (vrs, mt_videos) => {
		get().commonSendVrsParam(vrs, mt_videos, 'start')
	},
	/**创建录像按钮 */
	createMtsVideo: (result, type) => {
		get().commonMtsVideo(result, type)
	},
	/**请求 发送创建录像数据 */
	sendCreateParam: (vrs, mt_videos) => {
		get().commonSendVrsParam(vrs, mt_videos, 'create')
	},
	commonSendVrsParam: (vrs, videos, type) => {
		const meetingMoid: string = useMccStore.getState().mccInfo.meetingMoid
		let mt_videos: MtVideosProps[] = []
		videos.forEach((item) => {
			//过滤掉会议
			if (item.mt.mt_type !== 9) {
				const videoName = '' + replaceSpaceBk(item.mt.name || '') + buildNameTime() + '.asf'
				mt_videos.push({
					...item,
					...vrs,
					rec_file: vrs.rec_file ? vrs.rec_file + '.asf' : videoName,
					recorder_mode: 1,
				})
			}
		})
		let params: FetchStartVideoParamsProps = {
			meeting_id: meetingMoid,
			mt_videos: mt_videos,
		}
		if (type === 'start') {
			fetchStartVideo(params).then((res) => {
				if (res.success) {
					get().reload()
				} else {
					Alert(res.description || '')
				}
				//关闭弹窗
				get().setModalInfo({
					...defaultModalInfo,
				})
				//去掉勾选记录
				get().cancelParamsStoreCheck()
			})
		} else {
			fetchCreateSaveVideo(params).then((res) => {
				if (res.success) {
					get().reload()
				} else {
					Alert(res.description || '')
				}
				//关闭弹窗
				get().setModalInfo({
					...defaultModalInfo,
				})
				//去掉勾选记录
				get().cancelParamsStoreCheck()
			})
		}
	},
	rec: async (result, type) => {
		let videos = await get().justIsHadInVrsList(result)
		if (!videos) {
			return
		}
		const videoName = result[0] ? replaceSpaceBk(result[0].mt?.name || '') + buildNameTime() : ''
		get().setModalInfo({
			isShow: true,
			type: 'terminalRecording',
			videos: videos,
			modalBack: {
				vrs_id: '',
				vrs_name: '',
				publish_mode: 1,
				rec_file: videoName,
			},
		})
	},
	storeRecord: (data) => {
		const { recordRecIng } = get()
		if (data.state === 1) {
			const newDate = recordRecIng.map((item) => {
				if (item.id === data.id) {
					return data
				} else {
					return item
				}
			})
			set({
				recordRecIng: newDate,
			})
		}
	},
}))
export const useMccMtVideoStore = create(store)
